<?php

require_once(WSB_MODULES_PATH . 'cms/Url.php');

class Cms_XtensionController extends WSB_Controller_Action
{

	public function init()
	{
		parent::init(); // immer zuerst!
	    $this->_models = array('Cms_Model_DbTable_Xtension');
	}

    public function addAction()
	{
    	$descriptors = Cms_Model_DbTable_Xtension::getDescriptors();
    	if(count($descriptors) == 0) {
    		$this->render('no-modules');
    	} else {
    		// Infos fuer htmlTable-Viewhelper
	    	$this->view->descriptors = $descriptors;
			$this->view->columns = array(
				array('key' => 'name', 'label' => $this->_helper->Translate('name'), 'sortable' => 'true'),
				array('key' => 'class', 'label' => $this->_helper->Translate('class'), 'sortable' => 'true'),
				array('key' => 'links', 'label' => '')
			);
			$this->view->fields = array(
				array('key' => 'name'),
				array('key' => 'class'),
				array('key' => 'links', 'callback' => array('Cms_XtensionController', 'callbackEditLink'))
			);
			$this->view->settings = array('sortedBy' => array(
				'key' => 'name', 'dir' => 'desc')
			);
    		$this->render();
    	}
    }

    public function doAddAction()
	{
    	$class = $this->_getParam('class');
    	if(is_string($class) && !empty($class)) {
    		$descriptor = null;
    		foreach(Cms_Model_DbTable_Xtension::getDescriptors() AS $d) {
				if(strval($d->class) === $class) {
					$descriptor = $d;
					break;
				}
    		}

			if($descriptor instanceof Cms_Model_XtensionDescriptor) {

				$table = new Cms_Model_DbTable_Xtension();

                // Nur eine Instanz erlaubt
                if($descriptor->singleton == 1) {
                    $rows = $table->fetchAll('class="' . $descriptor->class . '"');
                    if($rows->count() >= 1) {
                        /**
                         * @todo: Flashmeldung ausgeben
                         */
        				$this->_helper->FlashMessenger->addMessage('Von diesem Modul kann nur eine Instanz erstellt werden.');
        				$this->_helper->Redirect($this->getDefaultAddUrl());
                    }
                }
                
				$item = $table->createRow();
				$item->class = $descriptor->class;
				$item->name = 'Neue Instanz --> ' . $descriptor->name;
				$item->deleted = 0;
				$item->save();

				$this->_importSql($descriptor->class);

				WSB_Log::info(sprintf('Added module %s with id %s', $descriptor->name, $item->id));

				$this->_helper->Redirect($this->getEditUrl($item->id));
			}
    	}
    	// Bei Fehler zurueck leiten
    	$this->_helper->Redirect($this->getDefaultAddUrl());
    }

    public function _importSql($moduleName)
	{
		try {
			$db = Zend_Db_Table_Abstract::getDefaultAdapter();
			$folder = '';
			switch(get_class($db)) {
				case 'Zend_Db_Adapter_Pdo_Mysql':
				case 'Zend_Db_Adapter_Mysqli':
					$folder = 'mysql';
					break;
				case 'Zend_Db_Adapter_Pdo_Sqlite':
					$folder = 'sqlite';
					break;
			}
	    	$sqlFile = sprintf(WSB_XTENSION_PATH . '%s/sql/%s/tables.sql', strtolower($moduleName), $folder);
	    	if(is_readable($sqlFile)) {
	    		$sql = file_get_contents($sqlFile);
	    		$sqlParts = WSB_Div::explode(';', $sql);
	    		foreach($sqlParts AS $sqlPart) {
	    			$sqlPart = trim($sqlPart);
	    			if(!empty($sqlPart)) {
						switch(get_class($db)) {
							case 'Zend_Db_Adapter_Mysqli':
								$stmt = new Zend_Db_Statement_Mysqli($db, $sqlPart);
								break;
							case 'Zend_Db_Adapter_Pdo_Mysql':
							case 'Zend_Db_Adapter_Pdo_Sqlite':
								$stmt = new Zend_Db_Statement_Pdo($db, $sqlPart);
								break;
						}
						$stmt->execute();
	    			}
	    		}
	    	}
		} catch(Exception $e) {
		}
    }

	public static function callbackEditLink(Cms_Model_XtensionDescriptor $descriptor)
	{
		return WSB_Controller_Url::getHtmlLink(WSB_Icon::add(), Cms_Url::xtensionDoAddUrl($descriptor->class));
	}

    /**
     * Uebersteuert WSB_Controller_Action::getDefaultAddUrl().
     *
     * @return string
     */
    public function getDefaultAddUrl()
	{
		return WSB_Controller_Url::getUrl('xtension', 'add', null, 'cms');
    }

	public function getEditUrl($id)
	{
		return WSB_Controller_Url::getUrl('xtension', 'edit', array('id' => $id), 'cms', array('redirect' => $this->getDefaultListUrl()));
	}

	public function buildListItemHtmlLinks(WSB_Db_Row $model, $modelIndex=0)
	{
		$links = array();
		array_push($links, $this->_buildEditListItemHtmlLink($model, $modelIndex));
		array_push($links, $this->_buildDeleteListItemHtmlLink($model, $modelIndex));
		array_push($links, $this->_buildHiddenListItemHtmlLink($model, $modelIndex));

		// Ueberpruefen, ob das Modul eine XT_Extension ist...
		// @todo: Vielleicht kann man dem Modul eine zusaetzliche Membervariable verpassen,
		// die Aufschluss gibt, ob es sich beim Modul um eine XT_Extension handelt?
		$isExtension = true;
		$descriptor = $model->getDescriptor();
		foreach($descriptor->controllers AS $controller) {
			foreach($controller AS $ctrl) {
				$ctrlClassName = strval($ctrl->class);
				$filename = str_replace(ucfirst($model->class).'_', '', $ctrlClassName).'.php';
				$dir = WSB_XTENSION_PATH . sprintf('%s/controllers/', strtolower($model->class));
				Zend_Loader::loadFile($filename, $dir, true);
				$ctrlObject = new $ctrlClassName();
				if(!$ctrlObject instanceof WSB_Xtension_Extension) {
					$isExtension = false;
					break 2;
				}
			}
		}
		if($isExtension) {
			array_push($links, WSB_Controller_Url::getHtmlLink(WSB_Icon::editXtContent(), Cms_Url::xtensionDefaultEditorUrl($model->getPrimaryValue())));
		}

		return $links;
	}

}
